<template>
  <div class="app-container">

    <!-- 查询和其他操作 -->
    <div class="filter-container">
      <el-button class="filter-item" :type="waiting" @click="handleFilter(0)">待审核</el-button>
      <el-button class="filter-item" :type="approval" @click="handleFilter(1)">已批准</el-button>
      <el-button class="filter-item" :type="rejected" @click="handleFilter(2)">已驳回</el-button>
    </div>
    <div class="filter-container">
      <el-select v-model="listQuery.userType" clearable style="width: 200px" class="filter-item" placeholder="商户类型">
        <el-option v-for="(item, index) in levelDic" :key="item" :label="item" :value="index" />
      </el-select>

      <el-date-picker
        v-model="listQuery.beginTime"
        type="datetime"
        :picker-options="pickerOptions1"
        placeholder="开始日期"
        align="right"
        style="width: 200px"
        class="filter-item"
      />
      <el-date-picker
        v-model="listQuery.endTime"
        type="datetime"
        :picker-options="pickerOptions2"
        placeholder="截止日期"
        align="right"
        style="width: 200px"
        class="filter-item"
      />
      <el-input
        v-model="listQuery.brandInput"
        placeholder="请输入品牌车型内容"
        align="right"
        style="width: 200px"
        class="filter-item"
        clearable
      />
      <el-button class="filter-item" type="primary" icon="el-icon-search" @click="handleFilter(listQuery.approveStatus)">查找</el-button>
    </div>

    <!-- 查询结果 -->
    <el-table v-loading="listLoading" :data="list" element-loading-text="正在查询中。。。" border fit highlight-current-row>

      <el-table-column align="center" label="车源编号" prop="code" />
      <el-table-column align="center" label="商户类型" prop="userType">
        <template slot-scope="scope">
          <el-tag :type="scope.row.userType === 0 ? '' : scope.row.userType === 1 ? 'success' : 'warning' ">{{ levelDic[scope.row.userType] }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column align="center" label="商户名" prop="shopName" />
      <el-table-column align="center" label="品牌车型" prop="herbGenericName,herbDescribe">
        <template slot-scope="scope"> {{ scope.row.herbGenericName }} {{ scope.row.herbDescribe }} </template>
      </el-table-column>
      <el-table-column align="center" label="上牌时间" prop="dueTime" />
      <el-table-column align="center" label="联系人" prop="contactName" />
      <el-table-column align="center" label="电话" prop="contactTel" />
      <el-table-column align="center" label="发布时间" prop="publishDt" />
      <el-table-column align="center" label="处理时间" prop="approveTime" />

      <el-table-column align="center" label="审核状态" prop="status">
        <template slot-scope="scope">
          <el-tag :type="scope.row.status === 1 ? 'success' : scope.row.status === 2 ? 'danger' : '' ">{{ statusDic[scope.row.status] }}</el-tag>
        </template>
      </el-table-column>

      <el-table-column align="center" label="操作" width="200" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button v-if="listQuery.approveStatus==0" type="primary" size="mini" @click="handleThrough(scope.row)">审核</el-button>
          <el-button v-if="listQuery.approveStatus!=0" type="primary" size="mini" @click="handleView(scope.row)">查看</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total>0" :total="total" :page.sync="listQuery.page" :limit.sync="listQuery.limit" @pagination="getList" />

    <!-- 添加或修改对话框 -->
    <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible">
      <el-form ref="dataForm" :rules="rules" :model="dataForm" status-icon label-position="left" label-width="130px" style="width: 400px; margin-left:50px;">

        <el-form-item label=" 联 系 人 :" prop="">
          <span class="form-span">{{ dataForm.contactName }}</span>
        </el-form-item>
        <el-form-item label="联 系 人 电 话 :" prop="">
          <span class="form-span">{{ dataForm.contactTel }}</span>
        </el-form-item>
        <el-form-item label="品牌 :" prop="">
          <span class="form-span">{{ dataForm.herbGenericName }}</span>
        </el-form-item>
        <el-form-item label="车型 :" prop="">
          <span class="form-span">{{ dataForm.herbDescribe }}</span>
        </el-form-item>
        <el-form-item label="车辆图片">
            <img v-for="(item, index) in listImages" :key="index" :src="item" class="avatar">
        </el-form-item>

        <el-form-item label="审 核 意 见 :" prop="approveRemark">
          <textarea style="width: 500px;height: 70px;" v-if="dialogStatus!='checkPending'" v-model="dataForm.approveRemark" maxlength="100" placeholder="审 核 意 见" readonly />
          <textarea style="width: 500px;height: 70px;" v-else v-model="dataForm.approveRemark" maxlength="100" placeholder="审 核 意 见"  />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" v-if="listQuery.approveStatus==0" @click="throughData" :loading="throughLoading">通过</el-button>
        <el-button type="danger" v-if="listQuery.approveStatus==0" @click="rejectedData" :loading="stepLoading">驳回</el-button>
        <el-button @click="dialogFormVisible = false">取消</el-button>
      </div>
    </el-dialog>

    <el-tooltip placement="top" content="返回顶部">
      <back-to-top :visibility-height="100" />
    </el-tooltip>

  </div>
</template>

<style>
  .form-span{
    width: 100%;
  }
  .table-expand {
    font-size: 0;
    padding-left: 60px;
  }
  .table-expand label {
    width: 100px;
    color: #99a9bf;
  }
  .table-expand .el-form-item {
    margin-right: 0;
    margin-bottom: 0;
  }
  .gallery {
    width: 80px;
    margin-right: 10px;
  }
  .herb-detail-box img {
    width: 100%;
  }
  .avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  width: 145px;
  height: 145px;
}
.avatar-uploader .el-upload:hover {
  border-color: #20a0ff;
}
.avatar{
    width: 145px;
    height: 145px;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 145px;
  height: 145px;
  line-height: 120px;
  text-align: center;
}
.avatar-uploader{
  line-height: 0px;
  width: 145px;
  height: 145px;
}
</style>

<script>
import { rejectedPurchaseAudit, fetchList, approvalPurchaseAudit } from '@/api/supplyAudit'
import BackToTop from '@/components/BackToTop'
import Pagination from '@/components/Pagination' // Secondary package based on el-pagination
import { thumbnail, toPreview } from '@/utils/index'

export default {
  name: 'purchaseAuditList',
  components: { BackToTop, Pagination },
  data() {
    return {
      listImages:[],
      thumbnail,
      toPreview,
      total: 0,
      stepLoading: false,
      throughLoading: false,
      listLoading: true,
      roleOptions: [],
      waiting: 'primary',
      approval: 'default',
      rejected: 'default',
      listQuery: {
        page: 1,
        limit: 20,
        userType: undefined,
        approveStatus: 0,
        companyName: undefined,
        sort: 'add_time',
        order: 'desc',
        beginTime: undefined,
        endTime: undefined,
        brandInput: undefined
      },
      pickerOptions1: {
        disabledDate: (time) => {
          if (this.listQuery.endTime != '') {
            return time.getTime() > Date.now() || time.getTime() > this.listQuery.endTime
          } else {
            return time.getTime() > Date.now()
          }
        }
      },
      pickerOptions2: {
        disabledDate: (time) => {
          return time.getTime() < this.listQuery.beginTime || time.getTime() > Date.now()
        }
      },

      dataForm: {
        companyName: undefined,
        adminUsername: undefined,
        adminPassword: undefined,
        adminRoleIds: undefined,
        approveRemark: undefined

      },
      list:[],
      herbList:'',
      dialogStatus: '',
      dialogFormVisible: false,
      rules: {
        approveRemark: [{ required: true, message: '审核意见不能为空', trigger: 'blur' }]
      },
      levelDic: ['个人', '车商', '经销商'],
      statusDic: ['待审核', '批准', '驳回'],
      textMap: {
        rejected: '已驳回',
        approval: '已批准',
        checkPending: '待审核'
      }
    }
  },
  created() {
    this.getList()
  },
  mounted() {
    // 绑定enter事件
    this.enterKeyup()
  },
  destroyed() {
    // 销毁enter事件
    this.enterKeyupDestroyed()
  },
  methods: {
    enterKey(event) {
      if (event.key == 'Enter') {
        this.handleFilter()
      }
    },
    enterKeyupDestroyed() {
      document.removeEventListener('keyup', this.enterKey)
    },
    enterKeyup() {
      document.addEventListener('keyup', this.enterKey)
    },
    getList() {
      this.listLoading = true
      fetchList(this.listQuery).then(response => {
        this.list = response.data.data.list
        this.total = response.data.data.total
        this.listLoading = false
      }).catch(() => {
        this.list = []
        this.total = 0
        this.listLoading = false
      })
    },
    handleFilter(state) {
      this.buttonChange(state)
      this.listQuery.approveStatus = state
      this.listQuery.page = 1
      this.getList()
    },
    buttonChange(state) {
      this.waiting = 'default'
      this.approval = 'default'
      this.rejected = 'default'
      if (state == '0') {
        this.waiting = 'primary'
      } else if (state == '1') {
        this.approval = 'primary'
      } else if (state == '2') {
        this.rejected = 'primary'
      }
    },
    // 弹出批准窗口
    handleThrough(row) {
        this.stepLoading=false
        this.throughLoading=false
        this.dataForm = Object.assign({}, row)
        this.dialogStatus = 'checkPending'
        this.dialogFormVisible = true
        const strArr = this.dataForm.herbListImage.split(',')
        this.listImages = strArr
        if(row.adminId){
        this.dataForm.adminRoleIds =this.queryRoleIds(row.adminId).map((t)=> Number(t))
        }else{
          this.dataForm.adminRoleIds=undefined
        }
        this.$nextTick(() => {
          this.$refs['dataForm'].clearValidate()
        })
    },
    // 弹出查看窗口
    handleView(row) {
        const self = this
        this.dataForm = Object.assign({}, row)
        const strList = this.dataForm.herbListImage.split(',')
        self.listImages = strList
        if(this.listQuery.approveStatus==2){
          this.dialogStatus = 'rejected'
          }else{
          this.dialogStatus = 'approval'
        }
        this.dialogFormVisible = true
        this.$nextTick(() => {
          this.$refs['dataForm'].clearValidate()
        })
    },
    // 查询角色
    queryRoleIds(id) {
      var that = this
      var data = {}
      data.adminId = id
      queryRoleIds(data).then(response => {
        this.dataForm.adminRoleIds = response.data.data
      }).catch(() => {

      })
    },
    // 批准审核
    throughData() {
      this.$refs['dataForm'].validate(valid => {
        if (valid) {
          this.throughLoading = true
          this.$confirm('此操作将批准审核, 是否继续?', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }).then(() => {
            approvalPurchaseAudit(this.dataForm)
              .then(() => {
                this.dialogFormVisible = false
                this.$notify.success({
                  title: '批准成功'
                })
                this.getList()
              })
              .catch(response => {
                this.throughLoading = false
                this.$notify.error({
                  title: '批准失败',
                  message: response.data.errmsg
                })
              })
          }).catch(() => {
            this.throughLoading = false
            this.$message({
              type: 'info',
              message: '已取消批准'
            })
          })
        }
      })
    },
    // 驳回审核
    rejectedData() {
      this.$refs['dataForm'].validate(valid => {
        if (valid) {
          this.stepLoading = true
          this.$confirm('此操作将驳回审核, 是否继续?', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }).then(() => {
            rejectedPurchaseAudit(this.dataForm)
              .then(() => {
                this.dialogFormVisible = false
                this.$notify.success({
                  title: '驳回成功'
                })
                this.getList()
              })
              .catch(response => {
                this.stepLoading = false
                this.$notify.error({
                  title: '驳回失败',
                  message: response.data.errmsg
                })
              })
          }).catch(() => {
            this.stepLoading = false
            this.$message({
              type: 'info',
              message: '已取消驳回'
            })
          })
        }
      })
    }
  }
}
</script>
